<template>
  <div 
    class="progress-bar"
    ref="progressRef"
    @click="handleClick"
    @mousedown="handleMouseDown"
  >
    <div class="progress" :style="{ width: progress + '%' }">
      <div 
        class="progress-btn"
        @mousedown.stop="handleBtnMouseDown"
      ></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

const props = defineProps<{
  currentTime: number
  duration: number
}>()

const emit = defineEmits<{
  (e: 'update:currentTime', value: number): void
}>()

const progressRef = ref<HTMLElement>()
const isDragging = ref(false)

const progress = computed(() => {
  return (props.currentTime / props.duration) * 100 || 0
})

const handleClick = (e: MouseEvent) => {
  if (!progressRef.value) return
  const rect = progressRef.value.getBoundingClientRect()
  const offsetWidth = progressRef.value.offsetWidth
  const percent = (e.clientX - rect.left) / offsetWidth
  emit('update:currentTime', percent * props.duration)
}

const handleMouseDown = (e: MouseEvent) => {
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
  handleClick(e)
}

const handleBtnMouseDown = () => {
  isDragging.value = true
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
}

const handleMouseMove = (e: MouseEvent) => {
  if (!progressRef.value) return
  const rect = progressRef.value.getBoundingClientRect()
  const offsetWidth = progressRef.value.offsetWidth
  let percent = (e.clientX - rect.left) / offsetWidth
  percent = Math.min(1, Math.max(0, percent))
  emit('update:currentTime', percent * props.duration)
}

const handleMouseUp = () => {
  isDragging.value = false
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)
}
</script>

<style scoped lang="scss">
.progress-bar {
  height: 4px;
  background: #e0e0e0;
  border-radius: 2px;
  cursor: pointer;
  position: relative;

  .progress {
    position: absolute;
    height: 100%;
    background: #409EFF;
    border-radius: 2px;

    .progress-btn {
      position: absolute;
      right: -6px;
      top: 50%;
      transform: translateY(-50%);
      width: 12px;
      height: 12px;
      background: white;
      border-radius: 50%;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
      cursor: pointer;
    }
  }
}
</style> 